<template>
  <div class="left-nav">
    <div class="logo">
      <img src="../assets/logo.png" alt="Logo" />
      <span>系统名称</span>
    </div>
    <el-menu
      :default-active="activeMenu"
      class="nav-menu"
      background-color="#304156"
      text-color="#fff"
      active-text-color="#409EFF"
      @select="handleSelect"
    >
      <el-sub-menu index="dashboard" popper-class="no-arrow">
        <template #title>
          <div class="sub-menu-title">
            <div class="menu-content">
              <el-icon><Monitor /></el-icon>
              <span>仪表板</span>
            </div>
            <el-dropdown 
              class="folder-actions" 
              trigger="click" 
              @command="(cmd) => handleAddCommand(cmd)"
              @click.stop
            >
              <el-icon class="action-icon" @click.stop><Setting /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="newDirectory" @click.stop>新建目录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
        
        <!-- 仪表板目录 -->
        <template v-for="folder in dashboardFolders" :key="folder.id">
          <el-sub-menu :index="folder.id" popper-class="no-arrow">
            <template #title>
              <div class="sub-menu-title">
                <el-icon><Folder /></el-icon>
                <span>{{ folder.name }}</span>
                <el-dropdown 
                  class="folder-actions" 
                  trigger="click" 
                  @command="(cmd) => handleAddCommand(cmd, folder)"
                  @click.stop
                >
                  <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="newDirectory" @click.stop>新建目录</el-dropdown-item>
                      <el-dropdown-item command="newForm" @click.stop>新建表单</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
            
            <!-- 子目录和表单 -->
            <template v-if="folder.children && folder.children.length > 0">
              <template v-for="item in folder.children" :key="item.id">
                <!-- 如果是目录 -->
                <el-sub-menu 
                  v-if="!item.type || item.type === 'dashboard'"
                  :index="item.id"
                  popper-class="no-arrow"
                >
                  <template #title>
                    <div class="sub-menu-title">
                      <el-icon><Folder /></el-icon>
                      <span>{{ item.name }}</span>
                      <el-dropdown 
                        class="folder-actions" 
                        trigger="click" 
                        @command="(cmd) => handleAddCommand(cmd, item)"
                        @click.stop
                      >
                        <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="newDirectory" @click.stop>新建目录</el-dropdown-item>
                            <el-dropdown-item command="newForm" @click.stop>新建表单</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </template>
                  
                  <!-- 子目录的表单 -->
                  <el-menu-item 
                    v-for="form in item.forms" 
                    :key="form.id" 
                    :index="form.id"
                    @click="handleFormClick(form)"
                  >
                    <div class="form-menu-item">
                      <div class="form-info">
                        <el-icon><Document /></el-icon>
                        <span>{{ form.name }}</span>
                      </div>
                      <el-dropdown 
                        class="form-actions" 
                        trigger="click" 
                        @command="(cmd) => handleFormCommand(cmd, form)"
                        @click.stop
                      >
                        <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="rename">重命名</el-dropdown-item>
                            <el-dropdown-item command="moveUp" :disabled="!canMoveUp(form)">上移</el-dropdown-item>
                            <el-dropdown-item command="moveDown" :disabled="!canMoveDown(form)">下移</el-dropdown-item>
                            <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </el-menu-item>
                </el-sub-menu>
                <!-- 如果是表单 -->
                <el-menu-item 
                  v-else
                  :index="item.id"
                  @click="handleFormClick({
                    id: item.id,
                    name: item.name,
                    type: 'form',
                    folderId: folder.id
                  })"
                >
                  <div class="form-menu-item">
                    <div class="form-info">
                      <el-icon><Document /></el-icon>
                      <span>{{ item.name }}</span>
                    </div>
                    <el-dropdown 
                      class="form-actions" 
                      trigger="click" 
                      @command="(cmd) => handleFormCommand(cmd, {
                        id: item.id,
                        name: item.name,
                        type: 'form',
                        folderId: folder.id
                      })"
                      @click.stop
                    >
                      <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="rename">重命名</el-dropdown-item>
                          <el-dropdown-item command="moveUp" :disabled="!canMoveUp(item)">上移</el-dropdown-item>
                          <el-dropdown-item command="moveDown" :disabled="!canMoveDown(item)">下移</el-dropdown-item>
                          <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </el-menu-item>
              </template>
            </template>
            
            <!-- 当前目录的表单 -->
            <el-menu-item 
              v-for="form in folder.forms" 
              :key="form.id" 
              :index="form.id"
              @click="handleFormClick(form)"
            >
              <div class="form-menu-item">
                <div class="form-info">
                  <el-icon><Document /></el-icon>
                  <span>{{ form.name }}</span>
                </div>
                <el-dropdown 
                  class="form-actions" 
                  trigger="click" 
                  @command="(cmd) => handleFormCommand(cmd, form)"
                  @click.stop
                >
                  <el-icon class="action-icon"><Setting /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="rename">重命名</el-dropdown-item>
                      <el-dropdown-item command="moveUp" :disabled="!canMoveUp(form)">上移</el-dropdown-item>
                      <el-dropdown-item command="moveDown" :disabled="!canMoveDown(form)">下移</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-sub-menu>
      
      <el-sub-menu index="report" popper-class="no-arrow">
        <template #title>
          <div class="sub-menu-title">
            <div class="menu-content" >
              <el-icon><Document /></el-icon>
              <span>报表管理</span>
            </div>
            <el-dropdown 
              class="folder-actions" 
              trigger="click" 
              @command="(cmd) => handleAddCommand(cmd)"
              @click.stop
            >
              <el-icon class="action-icon" @click.stop><Setting /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="newDirectory" @click.stop>新建目录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
        
        <!-- 顶层目录 -->
        <template v-for="folder in reportFolders" :key="folder.id">
          <el-sub-menu :index="folder.id" popper-class="no-arrow">
            <template #title>
              <div class="sub-menu-title" >
                <el-icon><Folder /></el-icon>
                <span>{{ folder.name }}</span>
                <el-dropdown 
                  class="folder-actions" 
                  trigger="click" 
                  @command="(cmd) => handleAddCommand(cmd, folder)"
                  @click.stop
                >
                  <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="newDirectory" @click.stop>新建目录</el-dropdown-item>
                      <el-dropdown-item command="newForm" @click.stop>新建表单</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
            
            <!-- 子目录 -->
            <template v-if="folder.children && folder.children.length > 0">
              <el-sub-menu 
                v-for="subFolder in folder.children" 
                :key="subFolder.id"
                :index="subFolder.id"
                popper-class="no-arrow"
              >
                <template #title>
                  <div class="sub-menu-title" >
                    <el-icon><Folder /></el-icon>
                    <span>{{ subFolder.name }}</span>
                    <el-dropdown 
                      class="folder-actions" 
                      trigger="click" 
                      @command="(cmd) => handleAddCommand(cmd, subFolder)"
                      @click.stop
                    >
                      <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="newDirectory" @click.stop>新建目录</el-dropdown-item>
                          <el-dropdown-item command="newForm" @click.stop>新建表单</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
                
                <!-- 子目录的表单 -->
                <el-menu-item 
                  v-for="form in subFolder.forms" 
                  :key="form.id" 
                  :index="form.id"
                  @click="loadFormDesigner(form)"
                >
                  <div class="form-menu-item">
                    <div class="form-info">
                      <el-icon><Document /></el-icon>
                      <span>{{ form.name }}</span>
                    </div>
                    <el-dropdown 
                      class="form-actions" 
                      trigger="click" 
                      @command="(cmd) => handleFormCommand(cmd, form)"
                      @click.stop
                    >
                      <el-icon class="action-icon" @click.stop><Setting /></el-icon>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="rename">重命名</el-dropdown-item>
                          <el-dropdown-item command="moveUp" :disabled="!canMoveUp(form)">上移</el-dropdown-item>
                          <el-dropdown-item command="moveDown" :disabled="!canMoveDown(form)">下移</el-dropdown-item>
                          <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </el-menu-item>
              </el-sub-menu>
            </template>
            
            <!-- 当前目录的表单 -->
            <el-menu-item 
              v-for="form in folder.forms" 
              :key="form.id" 
              :index="form.id"
              @click="loadFormDesigner(form)"
            >
              <div class="form-menu-item">
                <div class="form-info">
                  <el-icon><Document /></el-icon>
                  <span>{{ form.name }}</span>
                </div>
                <el-dropdown 
                  class="form-actions" 
                  trigger="click" 
                  @command="(cmd) => handleFormCommand(cmd, form)"
                  @click.stop
                >
                  <el-icon class="action-icon"><Setting /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="rename">重命名</el-dropdown-item>
                      <el-dropdown-item command="moveUp" :disabled="!canMoveUp(form)">上移</el-dropdown-item>
                      <el-dropdown-item command="moveDown" :disabled="!canMoveDown(form)">下移</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-sub-menu>

      <el-sub-menu index="settings">
        <template #title>
          <el-icon><Setting /></el-icon>
          <span>系统设置</span>
        </template>
        <el-menu-item index="settings:users">人员管理</el-menu-item>
        <el-menu-item index="settings:directories" @click="handleOpenDirectoryManager">目录管理</el-menu-item>
        <el-menu-item index="settings:permissions">权限管理</el-menu-item>
      </el-sub-menu>
    </el-menu>

    <!-- 新建目录弹窗 -->
    <el-dialog
      v-model="showNewDirDialog"
      title="新建目录"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="newDirForm" :rules="dirRules" ref="newDirFormRef">
        <el-form-item label="目录名称" prop="name">
          <el-input v-model="newDirForm.name" placeholder="请输入目录名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNewDirDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateDirectory">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建表单弹窗 -->
    <el-dialog
      v-model="showNewFormDialog"
      title="新建表单"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="newFormForm" :rules="formRules" ref="newFormFormRef">
        <el-form-item label="表单名称" prop="name">
          <el-input v-model="newFormForm.name" placeholder="请输入表单名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNewFormDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Monitor, Document, Setting, Plus, Folder } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import type { FormInstance } from 'element-plus'

// 配置后端API基础URL
const API_BASE_URL = 'http://localhost:5000/api'

interface FormDefinition {
  components: FormComponent[]
  layout: any
  settings: any
}

interface FormComponent {
  id: string
  type: string
  field: string
  label: string
  placeholder?: string
  rules?: any[]
  options?: { label: string; value: any }[]
  min?: number
  max?: number
  step?: number
  rows?: number
  dateType?: string
}

interface Form {
  id: string
  name: string
  type: string
  folderId: string
  definition?: FormDefinition
}

interface Folder {
  id: string
  name: string
  type: 'dashboard' | 'report'
  children: Folder[]
  forms: Form[]
}

interface NavResponse {
  code: number
  message: string
  data: Folder[]
}

const emit = defineEmits<{
  (e: 'select', index: string): void
  (e: 'create-form', form: Form): void
  (e: 'open-form-designer', form: Form): void
  (e: 'form-updated', form: Form): void
  (e: 'open-directory-manager', folders: Folder[]): void
  (e: 'preview-form', form: Form): void
}>()

const activeMenu = ref('dashboard')
const showNewDirDialog = ref(false)
const showNewFormDialog = ref(false)
const newDirForm = ref({ name: '' })
const newFormForm = ref({ name: '' })
const newDirFormRef = ref<FormInstance | null>(null)
const newFormFormRef = ref<FormInstance | null>(null)
const currentFolder = ref<Folder | null>(null)

// 表单校验规则
const dirRules = {
  name: [
    { required: true, message: '请输入目录名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

const formRules = {
  name: [
    { required: true, message: '请输入表单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 报表目录数据
const reportFolders = ref<Folder[]>([])

// 仪表板目录数据
const dashboardFolders = ref<Folder[]>([])

// 加载导航菜单数据
const loadNavData = async () => {
  try {
    // 加载仪表板目录结构
    const dashboardResponse = await axios.get(`${API_BASE_URL}/nav/dashboard/structure`)
    if (dashboardResponse.data.code === 0) {
      dashboardFolders.value = dashboardResponse.data.data || []
    }

    // 加载报表目录结构
    const reportResponse = await axios.get(`${API_BASE_URL}/nav/structure`)
    if (reportResponse.data.code === 0) {
      reportFolders.value = reportResponse.data.data || []
    }
  } catch (error) {
    console.error('加载导航数据错误:', error)
    ElMessage.warning('后端服务未连接，使用默认导航结构')
    reportFolders.value = []
    dashboardFolders.value = []
  }
}

// 保存导航菜单数据
const saveNavData = async () => {
  try {
    const response = await axios.post(`${API_BASE_URL}/nav/structure`, {
      structure: reportFolders.value
    })
    if (response.data.code === 0) {
      ElMessage.success('保存导航结构成功')
      return true
    } else {
      throw new Error(response.data.message || '保存导航结构失败')
    }
  } catch (error) {
    console.error('保存导航数据错误:', error)
    ElMessage.warning('后端服务未连接，导航结构将在服务恢复后保存')
    return true // 返回true以允许继续操作
  }
}

// 处理菜单选择
const handleSelect = (index: string) => {
  // 更新菜单选中状态
  activeMenu.value = index
  // 仅触发选择事件，不处理表单加载
  emit('select', index)
}

// 处理添加命令
const handleAddCommand = (command: string, folder?: Folder) => {
  if (folder) {
    currentFolder.value = folder
  } else {
    // 如果没有指定目录，使用根目录
    currentFolder.value = {
      id: 'root',
      name: '根目录',
      type: command === 'newDirectory' ? 'dashboard' : 'report',
      children: command === 'newDirectory' ? dashboardFolders.value : reportFolders.value,
      forms: []
    }
  }
  
  if (command === 'newDirectory') {
    showNewDirDialog.value = true
    // 清空表单
    newDirForm.value.name = ''
  } else if (command === 'newForm') {
    showNewFormDialog.value = true
    // 清空表单
    newFormForm.value.name = ''
  }
}

// 创建目录
const handleCreateDirectory = async () => {
  if (!newDirFormRef.value || !currentFolder.value) {
    ElMessage.error('请先选择目录')
    return
  }
  
  await newDirFormRef.value.validate(async (valid: boolean) => {
    if (valid && currentFolder.value) {
      // 检查是否存在重名目录
      let existingFolders = currentFolder.value.id === 'root' 
        ? (currentFolder.value.type === 'dashboard' ? dashboardFolders.value : reportFolders.value)
        : currentFolder.value.children || []

      const exists = existingFolders.some(child => child.name === newDirForm.value.name)
      if (exists) {
        ElMessage.error('目录名称已存在')
        return
      }

      // 添加新目录
      const newFolder: Folder = {
        id: `folder${Date.now()}`,
        name: newDirForm.value.name,
        type: currentFolder.value.type,
        children: [],
        forms: []
      }

      // 如果是根目录，直接添加到对应的目录列表
      if (currentFolder.value.id === 'root') {
        if (currentFolder.value.type === 'dashboard') {
          dashboardFolders.value = [...dashboardFolders.value, newFolder]
        } else {
          reportFolders.value = [...reportFolders.value, newFolder]
        }
      } else {
        if (!currentFolder.value.children) {
          currentFolder.value.children = []
        }
        currentFolder.value.children.push(newFolder)
      }

      // 保存到后端
      if (await saveNavData()) {
        showNewDirDialog.value = false
        newDirForm.value.name = ''
        // 重新加载数据以确保显示正确
        await loadNavData()
        ElMessage.success('目录创建成功')
      }
    }
  })
}

// 创建表单
const handleCreateForm = async () => {
  if (!newFormFormRef.value || !currentFolder.value) {
    ElMessage.error('请先选择目录')
    return
  }

  await newFormFormRef.value.validate(async (valid: boolean) => {
    if (valid && currentFolder.value) {
      // 如果是根目录，不允许创建表单
      if (currentFolder.value.id === 'root') {
        ElMessage.error('不能在根目录创建表单')
        return
      }

      // 确保forms数组存在
      if (!currentFolder.value.forms) {
        currentFolder.value.forms = []
      }
      
      // 检查是否存在重名表单
      const exists = currentFolder.value.forms.some(form => form.name === newFormForm.value.name)
      if (exists) {
        ElMessage.error('表单名称已存在')
        return
      }

      // 创建新表单，使用表单名称作为ID
      const formName = newFormForm.value.name
      const newForm: Form = {
        id: `${formName.toLowerCase().replace(/\s+/g, '_')}`,
        name: formName,
        type: 'form',
        folderId: currentFolder.value.id
      }

      try {
        // 先保存表单数据到后端，使用表单名称作为文件名
        const response = await axios.post(`${API_BASE_URL}/form/${formName}`, {
          id: newForm.id,
          name: newForm.name,
          components: [],
          layout: {},
          settings: {}
        })

        if (response.data.code === 0 && currentFolder.value) {
          currentFolder.value.forms.push(newForm)
          // 保存导航结构
          if (await saveNavData()) {
            showNewFormDialog.value = false
            newFormForm.value.name = ''
            // 重新加载数据以确保显示正确
            await loadNavData()
            // 打开表单设计器
            emit('open-form-designer', newForm)
            ElMessage.success('表单创建成功')
          }
        } else {
          throw new Error(response.data.message || '创建表单失败')
        }
      } catch (error) {
        console.error('创建表单错误:', error)
        ElMessage.error('创建表单失败，请检查网络连接')
      }
    }
  })
}

// 处理表单命令
const handleFormCommand = async (command: string, form: any) => {
  switch (command) {
    case 'rename':
      await handleRenameForm(form)
      break
    case 'moveUp':
      handleMoveForm(form, -1)
      break
    case 'moveDown':
      handleMoveForm(form, 1)
      break
    case 'delete':
      await handleDeleteForm(form)
      break
  }
}

// 重命名表单
const handleRenameForm = async (form: any) => {
  const { value: newName } = await ElMessageBox.prompt('请输入新的表单名称', '重命名表单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: form.name,
    inputPattern: /.+/,
    inputErrorMessage: '表单名称不能为空'
  })

  if (newName) {
    try {
      // 先获取当前表单数据
      const response = await axios.get(`${API_BASE_URL}/form/${form.id}`)
      const currentFormData = response.data.code === 0 ? response.data.data : null

      // 更新表单名称
      const updateResponse = await axios.post(`${API_BASE_URL}/form/${form.id}`, {
        ...form,
        name: newName,
        components: currentFormData?.components || [],
        layout: currentFormData?.layout || {},
        settings: currentFormData?.settings || {}
      })

      if (updateResponse.data.code === 0) {
        form.name = newName
        emit('form-updated', form)
        ElMessage.success('表单重命名成功')
      } else {
        throw new Error(updateResponse.data.message || '重命名失败')
      }
    } catch (error) {
      console.error('重命名表单错误:', error)
      ElMessage.warning('后端服务未连接，重命名将在服务恢复后保存')
      // 即使后端服务未连接，也允许继续操作
      form.name = newName
      emit('form-updated', form)
      ElMessage.success('表单重命名成功（离线模式）')
    }
  }
}

// 移动表单
const handleMoveForm = (form: any, direction: number) => {
  const currentFolder = findFolderById(form.folderId)
  if (!currentFolder) return

  const forms = currentFolder.forms || []
  const currentIndex = forms.findIndex((f: any) => f.id === form.id)
  const newIndex = currentIndex + direction

  if (newIndex >= 0 && newIndex < forms.length) {
    const temp = forms[currentIndex]
    forms[currentIndex] = forms[newIndex]
    forms[newIndex] = temp
  }
}

// 删除表单
const handleDeleteForm = async (form: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该表单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    try {
      // 先删除表单文件
      const response = await axios.delete(`${API_BASE_URL}/form/${form.id}`)
      if (response.data.code === 0) {
        // 从导航结构中移除表单
        const currentFolder = findFolderById(form.folderId)
        if (currentFolder) {
          currentFolder.forms = currentFolder.forms.filter((f: any) => f.id !== form.id)
          
          // 保存更新后的导航结构到后端
          if (await saveNavData()) {
            ElMessage.success('表单删除成功')
            if (activeMenu.value === form.id) {
              activeMenu.value = 'dashboard'
              emit('select', 'dashboard')
            }
            await loadNavData()
          }
        }
      } else {
        throw new Error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除表单错误:', error)
      ElMessage.warning('后端服务未连接，删除将在服务恢复后执行')
      // 即使后端服务未连接，也允许继续操作
      const currentFolder = findFolderById(form.folderId)
      if (currentFolder) {
        currentFolder.forms = currentFolder.forms.filter((f: any) => f.id !== form.id)
        if (activeMenu.value === form.id) {
          activeMenu.value = 'dashboard'
          emit('select', 'dashboard')
        }
        await loadNavData()
        ElMessage.success('表单删除成功（离线模式）')
      }
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除表单错误:', error)
      ElMessage.error(error.response?.data?.message || '删除失败，请检查网络连接')
      await loadNavData()
    }
  }
}

// 判断是否可以上移
const canMoveUp = (form: any) => {
  const currentFolder = findFolderById(form.folderId)
  if (!currentFolder) return false
  const forms = currentFolder.forms || []
  const currentIndex = forms.findIndex((f: any) => f.id === form.id)
  return currentIndex > 0
}

// 判断是否可以下移
const canMoveDown = (form: any) => {
  const currentFolder = findFolderById(form.folderId)
  if (!currentFolder) return false
  const forms = currentFolder.forms || []
  const currentIndex = forms.findIndex((f: any) => f.id === form.id)
  return currentIndex < forms.length - 1
}

// 根据ID查找文件夹
const findFolderById = (folderId: string) => {
  const findInFolder = (folders: any[]): any => {
    for (const folder of folders) {
      if (folder.id === folderId) return folder
      if (folder.children) {
        const found = findInFolder(folder.children)
        if (found) return found
      }
    }
    return null
  }
  return findInFolder(reportFolders.value)
}

// 处理表单点击
const handleFormClick = async (form: Form) => {
  try {
    // 获取表单定义
    const formResponse = await axios.get(`${API_BASE_URL}/form/${form.id}`)
    if (formResponse.data.code === 0) {
      const formDefinition = formResponse.data.data
      // 触发表单设计器事件
      emit('preview-form', {
        ...form,
        definition: formDefinition
      })
    } else {
      throw new Error(formResponse.data.message || '加载表单失败')
    }
  } catch (error) {
    console.error('加载表单错误:', error)
    ElMessage.error('加载表单失败，请检查网络连接')
  }
}

// 加载表单设计器
const loadFormDesigner = async (form: Form) => {
  try {
    // 先清除当前选中状态并更新activeMenu
    activeMenu.value = form.id
    
    // 获取表单定义
    const formResponse = await axios.get(`${API_BASE_URL}/form/${form.id}`)
    if (formResponse.data.code === 0) {
      const formDefinition = formResponse.data.data
      // 发送完整的表单数据
      const formData = {
        ...form,
        definition: formDefinition,
        key: Date.now() // 添加一个key强制更新
      }
      
      // 直接触发openFormDesigner事件
      emit('open-form-designer', formData)
    } else {
      throw new Error(formResponse.data.message || '加载表单失败')
    }
  } catch (error) {
    console.error('加载表单错误:', error)
    ElMessage.error('加载表单失败，请检查网络连接')
  }
}

// 在组件挂载时加载导航数据
onMounted(() => {
  loadNavData()
})

// 定义组件暴露的方法
defineExpose({
  loadNavData
})

// 处理目录管理点击
const handleOpenDirectoryManager = () => {
  // 发送目录管理事件，并传递当前的目录结构
  emit('open-directory-manager', [...dashboardFolders.value, ...reportFolders.value])
}
</script>

<style scoped>
.left-nav {
  height: 100%;
  position: relative;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #2b2f3a;
}

.logo img {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.logo span {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
}

.nav-menu {
  border-right: none;
}

.nav-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
}

.nav-menu :deep(.el-menu-item.is-active) {
  background-color: #263445 !important;
}

.folder-actions {
  opacity: 0;
  transition: opacity 0.3s;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  pointer-events: auto;
}

:deep(.el-sub-menu__title:hover) .folder-actions {
  opacity: 1;
}

.action-icon {
  font-size: 16px;
  color: #909399;
  cursor: pointer;
}

.action-icon:hover {
  color: #409EFF;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 隐藏箭头图标 */
:deep(.el-sub-menu__icon-arrow) {
  display: none !important;
}

/* 子菜单标题样式 */
.sub-menu-title {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
  padding-right: 40px;
}

.menu-content {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
}

.menu-content .el-icon {
  margin-right: 8px;
  flex-shrink: 0;
}

.menu-content span {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 确保设置按钮区域不会触发折叠/展开 */
.folder-actions {
  opacity: 0;
  transition: opacity 0.3s;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  pointer-events: auto;
}

:deep(.el-sub-menu__title) {
  /* padding-right: 20px !important; */
  position: relative;
}

:deep(.el-sub-menu__title:hover) .folder-actions {
  opacity: 1;
}

/* 确保下拉菜单正确显示 */
:deep(.el-dropdown__popper) {
  z-index: 3000 !important;
}

/* 防止点击事件冒泡 */
:deep(.el-dropdown-menu__item) {
  cursor: pointer;
}

.form-menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.form-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.form-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.form-menu-item:hover .form-actions {
  opacity: 1;
}
</style>

<script set lang="ts">
/**
 * @typedef {Object} Form
 * @property {string} id - 表单ID
 * @property {string} name - 表单名称
 */

/**
 * @typedef {Object} Folder
 * @property {string} id - 目录ID
 * @property {string} name - 目录名称
 * @property {Folder[]} children - 子目录
 * @property {Form[]} forms - 表单列表
 */

/**
 * @typedef {Object} NavResponse
 * @property {number} code - 响应代码
 * @property {string} message - 响应消息
 * @property {Folder[]} data - 导航数据
 */
</script> 